<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form divClass" v-if="headerShow">
                <div>
                    <a-form size="small" :model="queryData" layout="inline">
                        <a-form-item label="公司">
                            <a-cascader :options="pageData.corporateList" v-model="queryData.firmId" allow-clear
                                class="bacClass" :loading="pageData.corporateLoading" @press-enter="huiche"
                                popup-container="html" />
                        </a-form-item>
                        <a-form-item label="机台编号">
                            <!-- <a-select popup-container="html"  class="bacClass" v-model="queryData.jitai" :style="{ width: '200px' }"
                                :allowClear="true" :filter-option="false" @click="jitaiCx" allow-search @search="jitaiCxs">
                                <a-option v-for="item in queryData.jitais">
                                    {{ item.machineCode }}
                                </a-option>
                            </a-select> -->
                            <a-input class="bacClass" v-model="queryData.jitai" @press-enter="huiche" allow-clear
                                style="width: 200px"></a-input>
                        </a-form-item>
                    </a-form>
                </div>
                <div>
                    <Toolbar :items="['查询', '新增', '删除', '导出']" @select="selectHandler" @add="addHandler"
                        @del="delWeipaichan" @export="exports" style="float: right"></Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <template #pageTabel>
            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                    rowSelection="multiple" @grid-ready="gridReady" style="height: calc(100% - 45px)"
                    :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc"
                    :localeText="localeText1" @columnResized="onColumnResized" @columnMoved="onColumnMoved">
                </AgGridVuesCopys>
                <paginationCopys :page-size-options="pagingList1" :page-size="pagination.pageSize"
                    :current="pagination.page" :total="total" show-total show-jumper show-page-size @change="PageSize"
                    @page-size-change="change1" style="justify-content: center" />
            </a-spin>
        </template>

        <a-drawer :style="{ zIndex: 999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd"
            unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false" cancel-text="关闭" ok-text="保存">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" :model="formData" layout="horizontal">
                    <a-form-item label-col-flex="80px" label="公司" field="firmId"
                        :rules="[{ required: true, message: '公司必填' }]" :validate-trigger="['change', 'blur']">
                        <a-cascader :options="pageData.corporateList" @change="corporateChange"
                            v-model="formData.firmId" allow-clear class="bacClass" ref="corporateRef"
                            :loading="pageData.corporateLoading" popup-container="html" />
                    </a-form-item>
                    <a-form-item label="车间" label-col-flex="80px" field="workshopId"
                        :rules="[{ required: true, message: '车间必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html" class="bacClass" v-model="formData.workshopId" allow-clear>
                            <a-option :value="1">染部A</a-option>
                            <a-option :value="2">染部B</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="80px" field="machineCode" label="机台编号"
                        :rules="[{ validator: isChiese }, { required: true, message: '机台编号必填' }]"
                        :validate-trigger="['change', 'blur']">
                        <a-input class="bacClass" v-model="formData.machineCode" @blur="inputBlur1"
                            @change="changeName" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" field="machineTypeName" label="机台类型"
                        :rules="[{ required: true, message: '机台类型必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html" class="bacClass" v-model="formData.machineTypeName"
                            :loading="loading1" :allowClear="true" @search="handleSearch1" :filter-option="false"
                            allow-search @focus="focusSel1" @change="changeName">
                            <a-option v-for="item in pageData.typeList">{{ item.typeName }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="80px" field="areaName" label="所属区域"
                        :rules="[{ required: true, message: '所属区域必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html" class="bacClass" v-model="formData.areaName"
                            :loading="loading2" :allowClear="true" @search="handleSearch2" :filter-option="false"
                            allow-search @focus="focusSel2">
                            <a-option v-for="item in pageData.areaList">{{ item.areaName }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="80px" field="coordinate" label="位置号"
                        :rules="[{ required: true, message: '位置号必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html" class="bacClass" v-model="formData.coordinate"
                            :loading="loading" :allowClear="true" @search="handleSearch" :filter-option="false"
                            allow-search @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="80px" field="machineName" label="机台名称"
                        :rules="[{ required: true, message: '名称必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input class="bacClass" v-model="formData.machineName" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" field="machineNum" label="机器产能">
                        <a-input-number class="bacClass" :min="0" :max="9999999999" :precision="2"
                            v-model="formData.machineNum" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" field="specification" label="规格">
                        <a-input class="bacClass" v-model="formData.specification" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" field="tubeNum" label="管数">
                        <a-input-number class="bacClass" :min="1" :max="9999999999" :precision="0"
                            v-model="formData.tubeNum" />
                    </a-form-item>
                    <!-- <a-form-item field="coordinates" label="机台坐标">
                            <a-input v-model="formData.coordinate" />
                        </a-form-item> -->
                    <a-form-item label-col-flex="80px" field="remark" label="备注">
                        <a-textarea class="bacClass" placeholder="" v-model="formData.remark" :max-length="400"
                            allow-clear show-word-limit />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
        <a-modal v-model:visible="visible" title="二维码" ok-text="关闭" @ok="gbModal" :closable="false" :hide-cancel="true"
            :mask-closable="false">
            <a-space direction="vertical">
                <a-button type="primary" @click="print">打印</a-button>
                <div id="machinery" style="width: 400px">
                    <QrcodeVue :value="qrData.code"></QrcodeVue>
                    <div style="display: inline-block; vertical-align: top; margin-left: 15px">
                        <div style="width: 200px">公司:{{ qrData.firm }}</div>
                        <div style="width: 200px">机台编号:{{ qrData.jtCode }}</div>
                        <div style="width: 200px">机台名称:{{ qrData.jtName }}</div>
                        <div style="width: 200px">机台类别:{{ qrData.jtType }}</div>
                        <div style="width: 200px">所属区域:{{ qrData.jtFimli }}</div>
                    </div>
                </div>
            </a-space>
        </a-modal>
    </pageTabelLayout>
</template>


<script setup lang="ts">
import axios from 'axios'
import { onMounted, reactive, ref } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { useTableColumn, useTable, usePagination, useRowSelection, useRowKey } from '@/hooks/table'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'
import ModalDialog from '@/components/ModalDialog.vue'
import QrcodeVue from 'qrcode.vue'
import printJS from 'print-js'
import { FormInstance } from '@arco-design/web-vue/es/form'
import WHService from '@/service/wh'

import { localeText } from '@/api/aggridZw'
import { slicing } from '@/utils/caseFrimAndSecRig'
import { pagingList } from "@/api/paging";
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

const whService = new WHService()
const companyList = whService.companyList
const localeText1: any = ref(localeText)
const visible = ref(false)
//定义TS类型
interface Firm {
    name: string
    id: number
}

interface Cloth {
    code: string
}

interface MachineType {
    id: number | string
    code: string
    name: string
    maxCapacity: string
    //删除
    deleteState: number | string | undefined
    // 作废的状态
    obsoleteState: number | string | undefined
}

interface Machine {
    id: string
    serialNo: number
    code: string
    name: string
    machineTypeId: any
    machineTypeName: string
    // coordinate: string;
    areaId: any
    areaName: string
}

const rowKey = useRowKey('id')

interface gcTsObj {
    code: string
    company: string
    createDate: string
    createUser: string
    id: number
    isActive: boolean
    remark: any
    sortIndex: number
    updateDate: string
    updateUser: string
}

const gbModal = () => {
    visible.value = false
}

// 变动机台名称
const changeName = () => {
    window.setTimeout(() => {
        formData.machineName = formData.machineCode + '/' + formData.machineTypeName
    }, 100)
}
const total = ref(10)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
    pagination.page = val
    doRefresh()
}

function change1(val: any) {
    pagination.pageSize = val
    doRefresh()
}
//下拉框查询
// function selCxAll() {
//   post({
//     url: 'org/firmGroup/getFirmInfoByMap',
//     data: {
//       firmName: '',
//       department: '',
//     },
//   }).then((result) => {
//     if (result.code === 200) {
//       if (result.data.length == 0) {
//         queryData.gcList = []
//         gsDatas.value = []
//       } else {
//         queryData.gcList = result.data
//         gsDatas.value = result.data
//       }
//     }
//   })
// }

const qrData = reactive({
    id: 0,
    firm: '',
    jtCode: '',
    jtName: '',
    jtType: '',
    jtXy: '',
    jtFimli: '',
    code: '',
})

//生成条码
const GenerateBtn = (record: any) => {
    qrData.firm = record.firm
    qrData.jtCode = record.machineCode
    qrData.jtName = record.machineName
    qrData.jtType = record.machineTypeName
    // qrData.jtXy = record.coordinate;
    qrData.jtFimli = record.areaName
    qrData.code = JSON.stringify({
        // id: record.id,
        // firm: encodeURI(record.firm),
        // machineName: encodeURI(record.machineName),
        machineCode: record.machineCode,
        // machineTypeName: encodeURI(record.machineTypeName),
        // coordinate: encodeURI(record.coordinate),
        // areaName: encodeURI(record.areaName),
    })
    visible.value = true
}

const print = () => {
    printJS({
        printable: 'machinery',
        type: 'html',
        targetStyles: ['*'],
    })
}

let gc = reactive<gcTsObj[]>([])
gc = JSON.parse(localStorage.getItem('gc') || '{}')

//查询表单form和select绑定的数据
const queryData: any = reactive({
    firm: '',
    gcList: [],
    jitai: '',
    jitais: [],
})

//机台类别form和select绑定的数据
const typeData = reactive({
    types: '',
})

//所属区域form和select绑定的数据
const areaData = reactive({
    areas: '',
})

//下拉框和弹窗的数据变量
const pageData = reactive<{
    gcList: Firm[]
    //暂时，需要等后台返回的数据类型，再看定义ts
    typeList: any[]
    areaList: any[]
    nameList: any[]
    showAdd: boolean
    sideTitle: string
    codeValue: string
    showQrcode: boolean
    corporateList: any[]
    corporateId: string
    corporateLoading: boolean
    pageLoading: boolean
}>({
    //选择工厂下拉框数据
    gcList: [],
    //机台类别的下拉框数据
    typeList: [],
    //所属区域的下拉框数据
    areaList: [],
    nameList: [],
    //弹窗是否显示
    showAdd: false,
    //弹窗的标题
    sideTitle: '新增类型',
    //通过机台类型和机台名称动态生成二维码-动态绑定的数据变量
    codeValue: '',
    //是否显示和隐藏二维码的弹窗
    showQrcode: false,
    corporateList: [],
    corporateId: '',
    corporateLoading: false,
    pageLoading: false
})

let gsDatas = ref<any[]>([])
const headerShow = ref<boolean>(true)
onMounted(() => {
    getCorporateList()
    doRefresh()
    // selCxAll()
})

//修改
const editHandler = (record: any) => {
    //数据回填
    for (let key in record) {
        formData[key] = record[key]
    }
    if (formData.machineNum == null || formData.machineNum == undefined) {
        formData.machineNum = 0
    }
    // formData.id = Number(record.id)
    // formData.firm = record.firm
    // formData.machineCode = record.machineCode;
    // formData.machineName = record.machineName;
    //机台类别名称
    formData.machineTypeName = record.machineTypeName
    formData.firmId = record.firmId
    formData.firm = record.firm
    formData.machineTypeId = record.machineTypeName
    //机台坐标
    // formData.coordinate = record.coordinate;
    //机台区域名称
    formData.areaName = record.areaName
    formData.areaId = record.areaName
    formData.remark = record.remark
    //显示弹窗
    pageData.showAdd = true

    //弹窗的标题
    pageData.sideTitle = '修改机器设备维护'
}

//表格的列描述信息|
const columns = useTableColumn([
    {
        title: '序号',
        // 列信息的标识，对应表格的数据
        dataIndex: 'serialNo',
        key: 'serialNo',
        width: 150,
    },
    {
        title: '公司',
        dataIndex: 'firm',
        key: 'firm',
        width: 150,
    },
    {
        title: "车间",
        key: "workshop",
        dataIndex: "workshop",
    },
    {
        title: '机台编号',
        dataIndex: 'machineCode',
        width: 150,
        key: 'machineCode',
    },
    {
        title: '机台名称',
        dataIndex: 'machineName',
        width: 150,
        key: 'machineName',
    },
    {
        title: '机台类别',
        dataIndex: 'machineTypeName',
        key: 'machineTypeName',
        width: 150,
    },
    {
        title: '位置号',
        dataIndex: 'coordinate',
        width: 150,
        key: 'coordinate',
    },
    {
        title: '所属区域',
        dataIndex: 'areaName',
        width: 150,
        key: 'areaName',
    },
    {
        title: '机器产能',
        dataIndex: 'machineNum',
        width: 150,
        key: 'machineNum',
    },
    {
        title: '规格',
        dataIndex: 'specification',
        width: 150,
        key: 'specification',
    },
    {
        title: '管数',
        dataIndex: 'tubeNum',
        width: 150,
        key: 'tubeNum',
    },
    {
        title: '备注',
        dataIndex: 'remark',
        width: 150,
        key: 'remark',
    },
    {
        title: '创建人',
        dataIndex: 'createName',
        width: 150,
        key: 'createName',
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 200,
        key: 'createTime',
    },
    {
        title: '修改人',
        dataIndex: 'updateName',
        width: 150,
        key: 'updateName',
    },
    {
        title: '修改时间',
        dataIndex: 'updateTime',
        width: 200,
        key: 'updateTime',
    },
    {
        title: '生成条码',
        slotName: 'Barcode',
        width: 150,
        key: 'barcode',
    },
    {
        title: '操作',
        slotName: 'Operation',
        width: 150,
        key: 'operation',
        fixed: 'right',
    },
])

let tc: any[] = columns.map((o) => {
    let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
    }

    if (o.slotName === 'Barcode') {
        // obj['resizable'] = false
        // obj['filter'] = false
        // obj['sortable'] = false
        // obj["lockPosition"] = "right"

        obj['cellRenderer'] = {
            template: `<a-tag color="green" style="cursor:pointer" @click="a">生成条码</a-tag>`,
            setup(props: any) {
                const a = () => {
                    GenerateBtn(props.params.data)
                }
                return {
                    a,
                }
            },
        }
    }

    if (o.slotName === 'Operation') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = '100px'
        obj['cellRenderer'] = {
            template: `<el-button style="color:#165dff;"  type="info" link  @click="a">修改</el-button>`,
            setup(props: any) {
                const a = () => {
                    editHandler(props.params.data)
                }
                return {
                    a,
                }
            },
        }
    }

    return obj
})

let a = [
    {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
    },
]
tc = a.concat(tc)

//新增修改弹窗动态绑定的数据
const formData: any = reactive({
    id: 0,
    machineCode: '',
    machineName: '',
    firm: '',
    //机台类别名称3
    machineTypeName: '',
    machineTypeId: 0,
    //机台坐标
    // coordinate: '',
    //机台区域名称
    areaName: '',
    remark: '',
    areaId: 0,
    machineNum: 0,
    coordinate: '',
    firmId: '',
    workshopId: null,
    workshop: '',
    specification: '',
    tubeNum: null,
    colorTypeId: null,
})

//复选框选中的值
const { selectedRowKeys } = useRowSelection()

//此方法用于表格数据动态渲染
const table = useTable()

//表格的pagination分页的属性配置
const pagination = usePagination(doRefresh)

function doRefresh() {
    pageData.pageLoading = true
    updateGridState01()
    //发起分页查询的请求
    post({
        url: 'aps/dwMachine/getMachinePage',
        data: {
            page: pagination.page,
            size: pagination.pageSize,
            machineCode: queryData.jitai,
            firmId: queryData.firmId,
        },
    }).then((result: any) => {
        //如果后台返回的状态码为200才能执行后续操作
        if (result.code === 200) {
            //将后台返回的分页查询数据传入，这个方法可获取表格的数据dataList,动态渲染表格，表格的data属性动态绑定table.dataList即可实现动态渲染
            table.handleSuccess(result.data.list)
            //result.data.pages：总页数
            //使用这个方法，可以将pagination总页数pageCount改为-当前用户点击查询后台返回的总页数
            //传入完成之后，即可动态绑定表格渲染
            // pagination.setTotalSize(result.data.total);
            gridOption.value.setRowData(result.data.list)
            total.value = result.data.total
        }
    }).catch(console.log).finally(() => {
        pageData.pageLoading = false
    })
}

//查询
const selectHandler = () => {
    pagination.page = 1
    doRefresh()
}

// //导出的封装的方法
// function tableToXlsx(table: any, filename: any) {
//     const uri = 'data:application/vnd.ms-excel;base64,',
//         template = `<html>
//             <head><meta charset="UTF-8"></head>
//             <body><table border="1">${table.innerHTML}</table></body>
//         </html>`;

//     const a = document.createElement('a');
//     a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
//     a.download = filename;
//     a.click();
//     // document.removeChild(a);
// }

// //导出
// const prints = () => {
//     Modal.confirm({
//         title: '系统提示',
//         content: '是否导出列表数据',
//         onOk() {
//             let table = document.getElementsByTagName("table")[1]
//             tableToXlsx(table, '机器设备维护')

//         }
//     })
// }
const exports = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
    } else {
        //将表头拼接出来
        let head =
            '<th>公司</th><th>机台编号</th><th>机台名称</th><th>机台类别</th><th>所属区域</th><th>备注</th><th>创建人</th><th>创建时间</th><th>修改人</th><th>修改人时间</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
            return (
                gridOption.value
                    .getSelectedRows()
                    .map((o: any) => {
                        return o.id
                    })
                    .indexOf(o['id']) !== -1
            )
        })
        let body = ''
        nowRow.forEach(function (o) {
            body += '<tr><td>' + o['firm'] + '</td>'
            body += '<td>' + o['machineCode'] + '</td>'
            body += '<td>' + o['machineName'] + '</td>'
            body += '<td>' + o['machineTypeName'] + '</td>'
            body += '<td>' + o['areaName'] + '</td>'
            body += '<td>' + o['remark'] + '</td>'
            body += '<td>' + o['createName'] + '</td>'
            body += '<td>' + o['createTime'] + '</td>'
            body += '<td>' + o['updateName'] + '</td>'
            body += '<td>' + o['updateTime'] + '</td>'
            body += '</tr>'
        })
        tableToXlsx(head, '机器设备维护', body)
    }
}
const corporateRef = ref<any>()
const corporateChange = (event: any) => {
    formData.areaName = ''
    nextTick(() => {
        formData.firm = slicing(corporateRef.value.selectViewValue[0].label)
    })
}
// 获取公司列表
const getCorporateList = async () => {
    try {
        pageData.corporateLoading = true
        const res = await post({ url: 'org/baCompany/getTreeCompanyByUser' })
        if (res.code == 200) {
            pageData.corporateList = res.data
            return
        }
        Message.error(res.message)
    } catch (error: any) {
        pageData.corporateLoading = false
    } finally {
        pageData.corporateLoading = false
    }
}
function tableToXlsx(head: any, filename: any, body: any) {
    const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
              <head><meta charset="UTF-8"></head>
              <body><table border="1"><tr>${head}</tr>${body}</table></body>
          </html>`

    const a = document.createElement('a')
    a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
    a.download = filename
    a.click()
    document.removeChild(a)
}

// 表格准备事件
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}

//表格的弹窗的确认和取消
const formRef = ref<FormInstance>()
const sideOk = () => {
    formRef.value?.validate().then((err) => {
        if (!err) {
            let id1 = 0
            pageData.typeList.forEach((item: any) => {
                if (item.typeName == formData.machineTypeName) {
                    id1 = item.id
                }
            })
            let id2 = 0
            pageData.areaList.forEach((item: any) => {
                if (item.areaName == formData.areaName) {
                    id2 = item.id
                }
            })
            if (formData.machineNum == null || formData.machineNum == undefined) {
                formData.machineNum = 0
            }
            formData.workshop = formData.workshopId == 1 ? '染部A' : '染部B'
            if (pageData.sideTitle === '新增机器设备维护') {
                if (formData.machineNum == null || formData.machineNum == undefined) {
                    formData.machineNum = 0
                }
                post({
                    url: 'aps/dwMachine/addMachine',
                    data: [
                        {
                            id: null,
                            firm: formData.firm,
                            firmId: formData.firmId,
                            machineName: formData.machineName,
                            machineCode: formData.machineCode,
                            machineTypeId: id1,
                            machineTypeName: formData.machineTypeName,
                            // coordinate: formData.coordinate,
                            areaId: id2,
                            areaName: formData.areaName,
                            remark: formData.remark,
                            machineNum: formData.machineNum,
                            coordinate: formData.coordinate,
                        },
                    ],
                }).then((res: any) => {
                    if (res.code === 200) {
                        pageData.showAdd = false
                        doRefresh()
                        //提示
                        Message.success('新增成功')
                    } else Message.error(res.message)
                })
            } else {
                if (id1 != undefined) {
                    formData.machineTypeId = Number(id1)
                }
                if (id2 != undefined) {
                    formData['areaId'] = Number(id2)
                }
                post({
                    url: 'aps/dwMachine/updateMachine',
                    data: [formData],
                }).then((res: any) => {
                    if (res.code === 200) {
                        doRefresh()
                        pageData.showAdd = false
                        Message.success('修改成功')
                    } else {
                        Message.error(res.message)
                    }
                })
            }
        }
    })
}

//新增
const addHandler = () => {
    for (let item in formData) {
        formData[item] = ''
    }
    if (formData.machineNum == null || formData.machineNum == undefined) {
        formData.machineNum = 0
    }
    pageData.showAdd = true
    pageData.sideTitle = '新增机器设备维护'
}

const inputBlur1 = () => {
    formData.machineCode = formData.machineCode.toUpperCase()
}

//删除
const delWeipaichan = () => {
    // if (selectedRowKeys.value.length === 0) {
    //     Message.error('请先勾选')
    //     return
    // }
    if (gridOption.value.getSelectedRows() === 0) {
        Message.error('请先勾选')
        return
    }
    const isArray = selectedRowKeys.value.map((num) => {
        return Number(num)
    })

    Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
            //删除的请求
            post({
                url: 'aps/dwMachine/delMachine',
                // data: isArray
                data: gridOption.value.getSelectedRows().map((o: any) => {
                    return o.id
                }),
            }).then((res: any) => {
                if (res.code === 200) {
                    Message.success({
                        content: '删除成功',
                        duration: 5000,
                    })
                    pagination.page = 1
                    doRefresh()
                } else {
                    Message.error({
                        content: res.message,
                        duration: 5000,
                    })
                }
            })
        },
    })
}
//下拉框得到焦点
const focusSel1 = () => {
    selJq({ typeName: '' })
}
//获取下拉框的机械类别
const options1 = ref<any>(pageData.typeList)
const loading1 = ref(false)
const handleSearch1 = (value: any) => {
    if (value) {
        const ob = { typeName: value }
        loading1.value = true
        selJq(ob)
        options1.value = pageData.typeList
        loading1.value = false
    } else {
        options1.value = []
    }
}

//获取下拉框的机械类别
function selJq(val: any) {
    post({
        url: 'aps/dwMachineType/getFieldValue',
        data: val,
    }).then((res: any) => {
        if (res.code === 200) {
            pageData.typeList = res.data
        } else {
            Message.error({
                content: '查询失败！',
                duration: 5000,
            })
        }
    })
}

//下拉框得到焦点
const focusSel2 = () => {
    selQy('')
}
//获取下拉框的机械类别
const options2 = ref<any>(pageData.areaList)
const loading2 = ref(false)
const handleSearch2 = (value: any) => {
    if (value) {
        loading2.value = true
        selQy(value)
        options2.value = pageData.areaList
        loading2.value = false
    } else {
        options2.value = []
    }
}

//获取下拉框的机械类别
function selQy(val: any) {
    if (formData.firmId == '' || formData.firmId == undefined || formData.firmId == null) {
        Message.warning({
            content: '请先选择公司！',
            duration: 2000,
        })
        return
    }
    //获取所属区域下拉框数据
    post({
        url: 'aps/dwMachineArea/getFieldValueByFirm',
        data: {
            firm: formData.firm,
            firmId: formData.firmId,
            // areaName: val,
        },
    }).then((res: any) => {
        if (res.code === 200) {
            pageData.areaList = res.data
        } else {
            Message.error({
                content: '查询失败！',
                duration: 5000,
            })
        }
    })
}
const handleChange = (_data: any) => {
    table.handleSuccess(_data)
}
const changeFirm = () => {
    formData.areaName = ''
    pageData.areaList = []
}
//判断是否填写了中文
const isChiese = (value: string, cb: Function) => {
    return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
        }
        resolve()
    })
}
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
}
const jitaiCx = () => {
    chaxuns({ machineCode: '' })
}
const jitaiCxs = (val: any) => {
    chaxuns({ machineCode: val })
}
function chaxuns(val: any) {
    post({
        url: 'aps/dwMachine/getFieldValue',
        data: val,
    }).then((res: any) => {
        if (res.code == 200) {
            queryData.jitais = res.data
        }
    })
}

//下拉框得到焦点
const focusSel = () => {
    selCxAll123({ locationMark: '' })
}

//下拉数据
const options = ref<any>(pageData.nameList)
const loading = ref(false)
const handleSearch = (value: any) => {
    if (value) {
        const ob = { locationMark: value, deleteState: 0 }
        loading.value = true
        selCxAll123(ob)
        options.value = pageData.nameList
        loading.value = false
    } else {
        options.value = []
    }
}
//下拉框查询
function selCxAll123(val: any) {
    post({
        url: 'aps/dwLocationMarkSet/getFieldValue',
        data: val,
    }).then(({ data, code }: any) => {
        if (code === 200) {
            console.log(data)
            let dataList: any = []
            data.forEach(function (o: any) {
                dataList.push(o['locationMark'])
            })
            pageData.nameList = dataList
        } else {
            Message.error({
                content: '查询失败！',
                duration: 5000,
            })
        }
    })
}
const huiche = () => {
    doRefresh()
}
const pagingList1: any = ref(pagingList)
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('MachineryEquipment002', gridOption, colState, tc)
const onColumnMoved = () => {
    saveGridState01()
}
const onColumnResized = () => {
    saveGridState01()
}
</script>


<style scoped lang="less">
#select {
    background-color: white;
    border: 1px solid black;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;

}

:deep(.ag-cell.ag-cell-first-right-pinned:not(.ag-cell-range-left):not(.ag-cell-range-single-cell)) {
    text-align: center;
}
</style>